<template>
  <div ref="chartContainer" v-chart-resize class="chartContainer"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import 'echarts/theme/macarons'

const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  }
})

const chartContainer = ref(null)
let chart = null // 改为普通变量

const setOptions = (data) => {
  if (!chart) return

  chart.setOption({
    tooltip: {
      trigger: 'item',
      padding: 14,
      textStyle: {
        fontSize: 22
      }
    },
    legend: {
      type: 'scroll',
      top: '60%',
      bottom: '5%',
      left: 'center',
      orient: 'vertical',
      pageButtonPosition: 'end',
      pageButtonGap: 5,
      pageTextStyle: {
        color: '#fff'
      },
      formatter: (name) => {
        const total2 = data.reduce((prevResult, current) => prevResult + current.value, 0)
        let target = data.find((item) => item.name === name)?.value || 0

        let p = total2 <= 0 ? 0 : ((target / total2) * 100).toFixed(2)
        return ['{a|' + name + '}', '{b|' + target + '个}', '{c|' + p + '%}'].join('  ')
      },
      textStyle: {
        rich: {
          a: {
            width: 120,
            padding: [0, 0, 0, 10],
            fontSize: 24,
            color: '#fff'
          },
          b: {
            width: 120,
            fontSize: 28,
            color: '#fff'
          },
          c: {
            fontSize: 28,
            color: '#fff'
          }
        }
      }
    },
    grid: {
      containLabel: true
    },
    series: [
      {
        type: 'pie',
        center: ['50%', '30%'],
        radius: ['35%', '50%'],
        avoidLabelOverlap: true,
        label: {
          show: false,
          position: 'center',
          formatter: function (params) {
            return (params.percent ?? 0) + '%'
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 28,
            fontWeight: 'bold',
            color: '#fff'
          }
        },
        labelLine: {
          show: true
        },
        data: data
      }
    ]
  })
}

const initChart = () => {
  if (!chartContainer.value) return
  chart = echarts.init(chartContainer.value)
  setOptions(props.chartData)
}

// 监听数据变化
watch(
  () => props.chartData,
  (val) => {
    setOptions(val)
  },
  { deep: true }
)

onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style scoped>
.chartContainer {
  width: 100%;
  height: 100%;
}
</style>
